<template>
  <div class="register-container">
    <!-- 顶部导航栏 -->
    <div class="nav-header">
      <el-icon class="back-icon" @click="goBack"><ArrowLeft /></el-icon>
      <div class="page-title">{{ t('register.title') }}</div>
      <div class="placeholder"></div>
    </div>

    <!-- 主体内容 -->
    <div class="register-content">
      <div class="register-form">
        <!-- 手机号输入框 -->
        <div class="form-item" :class="{ 'error': errors.phone }">
          <el-icon><Iphone /></el-icon>
          <input
            v-model="registerForm.phone"
            :placeholder="t('register.phonePlaceholder')"
            class="form-input"
            type="text"
            @blur="validateField('phone')"
            @input="clearError('phone')"
          />
        </div>
        <div v-if="errors.phone" class="error-message">{{ errors.phone }}</div>

        <!-- 图片验证码 -->
        <div class="form-item" :class="{ 'error': errors.imageCaptcha }">
          <el-icon><Picture /></el-icon>
          <div class="captcha-container">
            <input
              v-model="registerForm.imageCaptcha"
              :placeholder="t('register.imageCaptchaPlaceholder')"
              class="form-input"
              type="text"
              @blur="validateField('imageCaptcha')"
              @input="clearError('imageCaptcha')"
            />
            <div class="image-captcha" @click="refreshCaptcha">
              <img :src="captchaImage" alt="验证码" />
            </div>
          </div>
        </div>
        <div v-if="errors.imageCaptcha" class="error-message">{{ errors.imageCaptcha }}</div>

        <!-- 短信验证码 -->
        <div class="form-item" :class="{ 'error': errors.captcha }">
          <el-icon><Message /></el-icon>
          <div class="captcha-container">
            <input
              v-model="registerForm.captcha"
              :placeholder="t('register.captchaPlaceholder')"
              class="form-input"
              type="text"
              @blur="validateField('captcha')"
              @input="clearError('captcha')"
            />
            <button
              type="button"
              class="captcha-button"
              :disabled="captchaDisabled || !canSendSms"
              @click="handleGetCaptcha"
            >
              {{ captchaText }}
            </button>
          </div>
        </div>
        <div v-if="errors.captcha" class="error-message">{{ errors.captcha }}</div>

        <!-- 密码输入框 -->
        <div class="form-item" :class="{ 'error': errors.password }">
          <el-icon><Lock /></el-icon>
          <input
            v-model="registerForm.password"
            type="password"
            :placeholder="t('register.passwordPlaceholder')"
            class="form-input"
            @blur="validateField('password')"
            @input="clearError('password')"
          />
        </div>
        <div v-if="errors.password" class="error-message">{{ errors.password }}</div>

        <!-- 同意条款 -->
        <div class="terms-checkbox">
          <el-checkbox v-model="agreeTerms" @change="validateAgreeTerms">
            {{ t('register.agreeTerms') }}
            <a href="#" @click.prevent="showTerms">{{ t('register.termsLink') }}</a>
          </el-checkbox>
        </div>

        <!-- 注册按钮 -->
        <el-button
          type="primary"
          class="register-button"
          :loading="loading"
          :disabled="!agreeTerms"
          @click="handleRegister"
        >
          {{ t('register.registerButton') }}
        </el-button>
      </div>
    </div>

    <!-- 服务条款对话框 -->
    <el-dialog
      v-model="termsDialogVisible"
      :title="t('register.termsTitle')"
      width="90%"
      top="15vh"
    >
      <div class="terms-content">
        <h3>{{ t('register.termsHeader') }}</h3>
        <p>{{ t('register.termsContent1') }}</p>
        <p>{{ t('register.termsContent2') }}</p>
        <p>{{ t('register.termsContent3') }}</p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="termsDialogVisible = false">{{ t('register.close') }}</el-button>
          <el-button type="primary" @click="acceptTerms">
            {{ t('register.accept') }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { useUserStore, useCaptchaStore } from 'store';
import { ElMessage } from 'element-plus';
import { ArrowLeft, Lock, Iphone, Message, Picture } from '@element-plus/icons-vue';
import  authService  from '@/services/authService';

// 国际化
const { t } = useI18n();

// 路由
const router = useRouter();

// Store
const userStore = useUserStore();
const captchaStore = useCaptchaStore();

// 表单数据
const registerForm = reactive({
  phone: '',
  imageCaptcha: '',
  captcha: '',
  password: ''
});

// 错误信息
const errors = reactive({
  phone: '',
  imageCaptcha: '',
  captcha: '',
  password: ''
});

// 同意条款
const agreeTerms = ref(false);

// 加载状态
const loading = ref(false);

// 验证码图片
const captchaImage = ref('');

// 验证码相关
const captchaTime = ref(0);
const captchaDisabled = computed(() => captchaTime.value > 0);
const captchaText = computed(() => {
  return captchaTime.value > 0 
    ? `${captchaTime.value}s` 
    : t('register.getCaptcha');
});

// 是否可以发送短信验证码
const canSendSms = computed(() => {
  return !errors.phone && !errors.imageCaptcha && registerForm.phone && registerForm.imageCaptcha;
});

// 计算属性：是否有错误
const hasErrors = computed(() => {
  return Object.values(errors).some(error => error !== '');
});

// 服务条款对话框
const termsDialogVisible = ref(false);

// 生命周期钩子
onMounted(() => {
  refreshCaptcha();
});

// 刷新验证码
const refreshCaptcha = () => {
  captchaImage.value = captchaStore.generateImageCaptcha();
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};

// 清除特定字段的错误
const clearError = (field) => {
  errors[field] = '';
};

// 验证特定字段
const validateField = (field) => {
  switch (field) {
    case 'phone':
      validatePhone();
      break;
    case 'imageCaptcha':
      validateImageCaptcha();
      break;
    case 'captcha':
      validateCaptcha();
      break;
    case 'password':
      validatePassword();
      break;
  }
};

// 验证所有字段
const validateAllFields = () => {
  validatePhone();
  validateImageCaptcha();
  validateCaptcha();
  validatePassword();
  
  return !hasErrors.value;
};

// 验证手机号
const validatePhone = () => {
  if (!registerForm.phone) {
    errors.phone = t('register.phoneRequired');
    return false;
  }
  if (!/^1[3-9]\d{9}$/.test(registerForm.phone)) {
    errors.phone = t('register.phoneFormat');
    return false;
  }
  errors.phone = '';
  return true;
};

// 验证图片验证码
const validateImageCaptcha = () => {
  if (!registerForm.imageCaptcha) {
    errors.imageCaptcha = t('register.imageCaptchaRequired');
    return false;
  }
  
  if (!captchaStore.verifyImageCaptcha(registerForm.imageCaptcha)) {
    errors.imageCaptcha = t('register.captchaError');
    return false;
  }
  
  errors.imageCaptcha = '';
  return true;
};

// 验证短信验证码
const validateCaptcha = () => {
  if (!registerForm.captcha) {
    errors.captcha = t('register.captchaRequired');
    return false;
  }
  
  if (registerForm.captcha.length < 4 || registerForm.captcha.length > 6) {
    errors.captcha = t('register.captchaLength');
    return false;
  }
  
  errors.captcha = '';
  return true;
};

// 验证密码
const validatePassword = () => {
  if (!registerForm.password) {
    errors.password = t('register.passwordRequired');
    return false;
  }
  if (registerForm.password.length < 6 || registerForm.password.length > 20) {
    errors.password = t('register.passwordLength');
    return false;
  }
  errors.password = '';
  return true;
};

const validateAgreeTerms = () => {
  if (!agreeTerms.value) {
    ElMessage.warning(t('register.mustAgreeTerms'));
  }
};

// 获取验证码
const handleGetCaptcha = async () => {
  // 验证手机号和图片验证码
  if (!validatePhone() || !validateImageCaptcha()) {
    return;
  }
  
  // 验证通过，发送验证码
  await authService.sendSmsCode(registerForm.phone, 1);
  // 发送成功，开始倒计时
  captchaStore.startSmsCountdown(registerForm.phone);
  captchaTime.value = 60;
  const timer = setInterval(() => {
    captchaTime.value--;
    if (captchaTime.value <= 0) {
      clearInterval(timer);
    }
  }, 1000);
};

// 注册处理
const handleRegister = async () => {
  // 表单验证
  if (!validateAllFields()) {
    return;
  }

  if (!agreeTerms.value) {
    ElMessage.warning(t('register.mustAgreeTerms'));
    return;
  }
  
  loading.value = true;
  try {
    // 构建注册请求数据
    const registerData = {
      phone: registerForm.phone,
      password: registerForm.password,
      code: registerForm.captcha,
      type: 1
    };
    
    const success = await authService.register(registerData);
    if (success) {
      ElMessage.success(t('register.registerSuccess'));
      router.push('/login');
    } else {
      // 注册失败，刷新验证码
      refreshCaptcha();
      registerForm.imageCaptcha = '';
    }
  } finally {
    loading.value = false;
  }
};

// 显示服务条款
const showTerms = () => {
  termsDialogVisible.value = true;
};

// 接受服务条款
const acceptTerms = () => {
  agreeTerms.value = true;
  termsDialogVisible.value = false;
};
</script>

<style scoped lang="scss">
.register-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 50px;
  padding: 0 15px;
  background-color: #3a4a6d;
  color: white;
  position: relative;

  .back-icon {
    font-size: 20px;
    cursor: pointer;
  }

  .page-title {
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    font-size: 18px;
    font-weight: 500;
  }

  .placeholder {
    width: 20px;
  }
}

.register-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
}

.register-form {
  margin-top: 20px;
}

.form-item {
  display: flex;
  align-items: center;
  background-color: white;
  border-radius: 4px;
  margin-bottom: 5px;
  padding: 0 15px;
  height: 50px;
  border: 1px solid transparent;
  transition: all 0.3s;

  &.error {
    border-color: #f56c6c;
  }

  .el-icon {
    margin-right: 10px;
    color: #999;
  }

  .form-input {
    flex: 1;
    border: none;
    outline: none;
    height: 100%;
    width: 100%;
    font-size: 16px;
    background: transparent;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin: -2px 0 10px 15px;
  height: 18px;
}

.captcha-container {
  display: flex;
  flex: 1;
  gap: 10px;

  .form-input {
    flex: 1;
  }

  .captcha-button {
    width: 100px;
    height: 36px;
    padding: 0;
    font-size: 12px;
    background-color: #3a4a6d;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    
    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
  }
  
  .image-captcha {
    width: 100px;
    height: 36px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    
    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
      border-radius: 4px;
    }
  }
}

.terms-checkbox {
  margin: 15px 0;
  padding: 0 5px;
  
  a {
    color: #3a4a6d;
  }
}

.register-button {
  width: 100%;
  height: 44px;
  margin-top: 20px;
  border-radius: 4px;
  font-size: 16px;
  background-color: #3a4a6d;
  border: none;
}

.terms-content {
  max-height: 300px;
  overflow-y: auto;
  padding: 0 10px;

  h3 {
    margin-top: 0;
  }

  p {
    line-height: 1.6;
  }
}
</style>